package com.fingard.dsp.bank.directbank.spdb12;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.spdb12.util.WtpFileUtil;
import com.fingard.dsp.bank.directbank.spdb12.util.YBTSeqNumUtil;
import com.fingard.dsp.bank.helpers.SeqBatchInfo;
import com.fingard.dsp.bank.helpers.SeqBatchInfoHelper;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SPDB12Contract extends SPDB12Base implements IContract {
    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;

        try {
            StringBuilder reqMsg = new StringBuilder();
            if ("01".equals(p_req.contractDetail.step)) {
                String cardType = p_req.contractDetail.cardType;
                if (StringHelper.isNullOrEmpty(cardType)) {
                    cardType = "2";
                } else if ("1".equals(cardType)) {
                    cardType = "2";// 存折
                } else {
                    cardType = "1";// 卡
                }
                String certType = convertCertTypeToBank(p_req.contractDetail.certType);

                String useCode = p_req.contractDetail.insuPolicyNum;

                // 签约序号※客户账户类型※客户账号※姓名※证件种类※证件号码※第三方号码※操作标志※是否浦发代销客户※备注1※备注2※密文\n
                StringBuilder sbFileContent = new StringBuilder();
                String tmpReqBodyDetail = MessageFormat.format("※{0}※{1}※{2}※{3}※{4}※{5}※1※1※{6}※※\n", cardType, p_req.contractDetail.payAct, p_req.contractDetail.payName, certType, p_req.contractDetail.certNum, useCode, p_req.contractDetail.askNumber);
                sbFileContent.append(tmpReqBodyDetail);

                String tmpReqData = sbFileContent.toString();
                WriteBankLogStep2(tmpReqData);

                // 上传文件名保存本地，查询时用
                Date tmpPayDateTime = getDayCutTime(new Date());
                SeqBatchInfo batInfo = new SeqBatchInfo();
                batInfo.loadFromReqBat(p_req);
                SeqBatchInfoHelper seqBatHelper = new SeqBatchInfoHelper(p_req.reqHeader.tenant, tmpPayDateTime);
                batInfo.batSeqNo = seqBatHelper.getNextBatSeq(batInfo, 0);
                String tmpBatSeqNo = getBatSeqNo(batInfo.batSeqNo);

                String tmpUpFilePrefix = "UBCS_" + bankFront.corpNo + "_" + bankFront.org + "_" + Format.Date8Format.format(tmpPayDateTime) + "_" + tmpBatSeqNo;
                String tmpUpFileName = tmpUpFilePrefix + ".txt";
                batInfo.upFileName = tmpUpFileName;
                String tmpLocalMarkPath = StringHelper.trimEnd(getDataFileDirectory(tmpPayDateTime), File.separator) + File.separator + tmpUpFileName;
                WriteBankLogLn2("当前签约明细请求文件本机保存路径: " + tmpLocalMarkPath);
                batInfo.upFilePath = tmpLocalMarkPath;
                batInfo.reqBatchNo = p_req.contractDetail.askNumber;

                seqBatHelper.insertSeqBatchInfo(batInfo);
                StringBuilder sbLog = new StringBuilder();
                boolean saved = YBTSeqNumUtil.saveSendDate(p_req.contractDetail.askNumber, Format.Date8Format.format(tmpPayDateTime), sbLog);
                if(!saved){
                    throw new Exception(sbLog.toString());
                }
                FileHelper.appendFile(tmpLocalMarkPath, tmpReqData, getCharset());

                tmpRetDetail.respCode = "0";
                tmpRetDetail.signConfirmType = "5";
                tmpRetDetail.unifiedCode = "SC004";
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        try {
            HashMap<String, String> mapSeqNum = YBTSeqNumUtil.getSendDate(p_reqQry.contractDetail.askNumber);
            if (mapSeqNum.isEmpty()) {
                // 未发生签约申请
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signState = ContractState.UNSIGNED;
                tmpRetDetail.signConfirmType = "5";
                tmpRetDetail.unifiedCode = "SC0000";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }

            Date tmpPayDateTime = getDayCutTime(Format.Date8Format.parse(mapSeqNum.get(p_reqQry.contractDetail.askNumber)));
            String tmpPaySendDate = Format.Date8Format.format(tmpPayDateTime);

            SeqBatchInfoHelper seqBatHelper = new SeqBatchInfoHelper(p_reqQry.reqHeader.tenant, tmpPayDateTime);
            SeqBatchInfo batInfo = seqBatHelper.loadFromDb(p_reqQry.reqHeader.bankCode, p_reqQry.contractDetail.askNumber);
            if (batInfo == null) {
                // 未发生签约申请
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signState = ContractState.UNSIGNED;
                tmpRetDetail.signConfirmType = "5";
                tmpRetDetail.unifiedCode = "SC0000";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String tmpBatSeqNo = getBatSeqNo(batInfo.batSeqNo);
            String tmpUpFilePrefix = "UBCS_" + bankFront.corpNo + "_" + bankFront.org + "_" + tmpPaySendDate + "_" + tmpBatSeqNo;
            String tmpDownFileName = tmpUpFilePrefix + ".txt";
            String tmpLocalMarkPath = StringHelper.trimEnd(getTempFileDirectory(), File.separator) + File.separator + tmpDownFileName;
            WriteBankLogLn2("批量授权结果文件保存本机路径: " + tmpLocalMarkPath);

            FtpSet ftpSet1 = bankFront.getFtpSet("contract");
            FtpReceiver ftpReceiver = null;
            String listFileName = "";
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet1);
                ftpReceiver = sftpPortClient.listFiles(ftpSet1.upDir);
                listFileName = ftpReceiver.connMsg;
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet1);
                ftpPortClient.setLocalPassiveMode();
                ftpReceiver = ftpPortClient.listFiles(ftpSet1.upDir);
                listFileName = ftpReceiver.connMsg;
                ftpPortClient.disconnect();
            }
            WriteBankLogLn("银行返回文件名列表:\r\n" + listFileName);

            boolean isMatched = false;
            String[] fileNames = listFileName.split(",");
            for(String fileName : fileNames) {
                if (tmpDownFileName.equalsIgnoreCase(fileName)) {
                    isMatched = true;
                }
            }
            if (isMatched) {
                tmpDownFileName = tmpDownFileName.replace("UBCS","DBCS");
                Map<String, Object> tmpRetMap = WtpFileUtil.wtpDownload(bankFront.serverURL, tmpDownFileName);
                WriteBankLogLn("wtp下载结果map内容:\r\n");
                Iterator<String> iterator = tmpRetMap.keySet().iterator();
                while(iterator.hasNext()) {
                    String retMapKey = iterator.next();
                    WriteBankLogLn(retMapKey+":" +tmpRetMap.get(retMapKey));
                }

                String mapRespCode = (String) tmpRetMap.get("RespCode");
                if (StringHelper.isNullOrEmpty(mapRespCode)) {
                    // 下载成功
                    Map<String,String> ftpMap = (Map<String, String>) tmpRetMap.get("Result");
                    WriteBankLogLn("wtp下载结果Result内容:\r\n");
                    Iterator<String> tmpIterator = ftpMap.keySet().iterator();
                    while(tmpIterator.hasNext()) {
                        String retMapKey = tmpIterator.next();
                        WriteBankLogLn(retMapKey+":" +ftpMap.get(retMapKey));
                    }

                    FtpSet ftpSet = new FtpSet();
                    ftpSet.serverIP = ftpMap.get("wtpHost");
                    ftpSet.port = Integer.parseInt(ftpMap.get("wtpPort"));
                    ftpSet.userName = ftpMap.get("userName");
                    ftpSet.userPassword = ftpMap.get("passWord");
                    ftpSet.downDir = ftpMap.get("filePath");

                    if (requestType != null && "SFTP".equals(requestType)) {
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        ftpReceiver = sftpPortClient.downloadFile("", tmpDownFileName, tmpLocalMarkPath);
                        listFileName = ftpReceiver.connMsg;
                        sftpPortClient.disconnect();
                    } else {
                        FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                        ftpPortClient.setLocalPassiveMode();
                        ftpReceiver = ftpPortClient.downloadFileFromDir(ftpSet.downDir, tmpDownFileName, tmpLocalMarkPath);
                        listFileName = ftpReceiver.connMsg;
                        ftpPortClient.disconnect();
                    }
                    if (ftpReceiver.isCompleted) {
                        String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                        WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                        if (StringHelper.hasAnyChar(tmpStrRet)) {
                            tmpRetDetail.respCode = "0";

                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            tmpReader.readLine();
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                String[] eachNodes = eachline.split("※");
                                String payAct = eachNodes[2].trim();
                                if (p_reqQry.contractDetail.payAct.equalsIgnoreCase(payAct)) {
                                    String errCode = eachNodes[9].trim();
                                    if ("AAAA".equalsIgnoreCase(errCode)) {
                                        tmpRetDetail.signState = ContractState.SUCCESS;
                                    } else {
                                        tmpRetDetail.signState = ContractState.FAIL;
                                    }
                                    tmpRetDetail.payAct = eachNodes[2].trim();
                                    tmpRetDetail.payName = eachNodes[3].trim();
                                    tmpRetDetail.certNum = eachNodes[5].trim();
                                    tmpRetDetail.signConfirmType = "5";
                                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", errCode);
                                }
                            }
                            tmpReader.close();
                            strReader.close();
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = "本地签约结果文件内容为空!";
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = "签约结果文件下载失败:" + ftpReceiver.connMsg;
                    }
                } else {
                    // 下载失败
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = (String) tmpRetMap.get("RespInfo");
                }
            } else {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signState = "signPending";
                tmpRetDetail.signConfirmType = "5";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}